<template>

 <!-- 在template部分添加对话框 -->
<el-dialog v-model="dialogVisible" title="上架新小说" width="50%">
  <el-form :model="formData" label-width="100px">
     <!-- <el-form-item label="小说id" required>
      <el-input v-model="formData.id" placeholder="请输入小说id" />
    </el-form-item> -->
    <el-form-item label="小说名称" required>
      <el-input v-model="formData.name" placeholder="请输入小说名称" />
    </el-form-item>
    <el-form-item label="封面链接">
      <el-input v-model="formData.cover_img" placeholder="请输入封面图片URL" />
    </el-form-item>
    <el-form-item label="出版社">
      <el-input v-model="formData.publisher" placeholder="请输入出版社" />
    </el-form-item>
    <el-form-item label="发行日期">
      <el-date-picker v-model="formData.publish_date" type="date" placeholder="选择日期" />
    </el-form-item>
    <!-- 在el-dialog中添加update_time字段 -->
<el-form-item label="更新时间" required>
  <el-input v-model="formData.update_time" placeholder="请输入更新时间格式YYYY-MM-DD HH:MM" />
</el-form-item>
    <el-form-item label="备注">
      <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="dialogVisible = false">取消</el-button>
    <el-button type="primary" @click="submitForm">确定</el-button>
  </template>
</el-dialog>
  <!-- 小说列表 -->
  <el-form :inline="true" class="demo-form-inline">
    <el-form-item label="小说名称:">
      <el-input v-model="productPage.query" placeholder="请输入小说名称" clearable />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="fetchNovels">查询</el-button>
      <!-- <el-button type="primary" @click="onLine">上架图书</el-button> -->
    </el-form-item>
  </el-form>
  
  <!-- 数据表格 -->
  <el-table :data="productData" style="width: 100%">
    <el-table-column fixed prop="id" label="编号" width="60" />
    <el-table-column prop="name" label="小说名称" width="180" />
    <el-table-column prop="cover_img" label="封面" width="90">
      <template #default="scope">
        <img :src="scope.row.cover_img" alt="封面" width="60" height="80">
      </template>
    </el-table-column>
    <el-table-column prop="publisher" label="出版社" width="150" />
    <el-table-column prop="publish_date" label="发行日期" width="120" />
    <el-table-column label="更新时间" width="160">  <!-- 修改为自定义标签 -->
      <template #default="scope">
        {{ formatUpdateTime(scope.row.update_time) }}
      </template>
    </el-table-column>
    <el-table-column prop="status" label="状态" width="90">
      <template #default="scope">
        <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
          {{ scope.row.status === 0 ? '正常' : '下架' }}
        </el-tag>
      </template>
    </el-table-column>
    
    <el-table-column fixed="right" label="操作" width="180">
      <template #default="scope">
        <el-button size="small" @click="handleStatus(scope.row)">
          {{ scope.row.status === 0 ? '下架' : '上架' }}
        </el-button>
        <el-button type="primary" size="small" @click="editItem(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 在表格下方添加分页组件 -->
  <el-pagination
    v-model:current-page="productPage.pageNum"
    v-model:page-size="productPage.pageSize"
    :page-sizes="[5, 10, 15, 20]"
    :total="total"
    layout="total, sizes, prev, pager, next, jumper"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin: 20px"
  />
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'  // 补充Element Plus消息导入

const productData = ref([])
const productPage = ref({
  query: '',
  pageNum: 1,
  pageSize: 5
})
const total = ref(0)

// 日期格式化函数（关键修改）
// 修改为直接返回原始字符串
const formatUpdateTime = (timeStr) => {
  return timeStr || '未设置'  // 直接返回原始字符串或默认值
}

// 获取小说数据（关键修改）
const fetchNovels = async () => {
  try {
    const response = await axios.get('http://localhost:8000/user/novels/', {
      params: {
        search: productPage.value.query,
        page: productPage.value.pageNum,
        page_size: productPage.value.pageSize
      }
    })
    productData.value = response.data.data
    total.value = response.data.total
  } catch (error) {
    console.error('数据加载失败:', error)
    ElMessage.error('数据加载失败，请检查网络连接')
  }
}


const dialogVisible = ref(false)
const formData = ref({
  name: '',
  cover_img: '',
  publisher: '',
  publish_date: '',
  status: 0,
  remark: ''
})

const onLine = () => {
  dialogVisible.value = true
}



// 提交表单
// const submitForm = async () => {
//   try {
//     const response = await axios.post('http://localhost:8000/user/novels/create/', formData.value)
//     ElMessage.success('小说上架成功')
//     dialogVisible.value = false
//     fetchNovels() // 刷新列表
//     resetForm() // 重置表单
//   } catch (error) {
//     ElMessage.error('上架失败: ' + (error.response?.data?.message || '服务器错误'))
//   }
// }












// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    cover_img: '',
    publisher: '',
    publish_date: '',
    status: 0,
    remark: ''
  }
}






const handleStatus = async (row) => {
  try {
    await axios.delete(`http://localhost:8000/user/novels/${row.id}/`)
    ElMessage.success('小说删除成功')
    fetchNovels() // 刷新列表数据
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败: ' + error.response?.data?.message || '服务器错误')
  }
}


// 初始化加载（保持不变）
onMounted(() => {
  fetchNovels()
})

// 其他方法（保持不变）
const onDelete = () => {}
const editItem = () => {}

// 新增分页事件处理
const handleSizeChange = (newSize) => {
  productPage.value.pageSize = newSize
  productPage.value.pageNum = 1
  fetchNovels()
}

const handleCurrentChange = (newPage) => {
  productPage.value.pageNum = newPage
  fetchNovels()
}
</script>

<style scoped>
.el-form {
  margin: 20px;
}

.el-table {
  margin: 0 20px;
}

img {
  object-fit: cover;
  border-radius: 4px;
}
</style>